


const httpsRE = /^https:\/\//;
const wsRE = /^ws(s)?:\/\//;


function parseProxyEnv(env, prefix = "VITE_PROXY_") {
    const proxyEntries = Object.entries(env)
        .filter(([key]) => key.startsWith(prefix))
        .map(([key, val]) => {
            const [context, target] = val.split("|");
            return { context, target };
        });

    return proxyEntries;
}

export function createProxy(env) {
    const proxyConfig = {};

    const entries = parseProxyEnv(env);

    for (const { context, target } of entries) {
        if (!target) continue;

        const isHttps = httpsRE.test(target);
        const isWs = wsRE.test(target);

        const config = {
            target,
            changeOrigin: true,
            ...(isHttps ? { secure: false } : {}),
        };

        // 添加 ws 支持
        if (isWs) {
            config.ws = true;
            config.rewriteWsOrigin = true;
        }

        // 默认重写规则（可根据需要自定义更智能的规则）
        config.rewrite = (path) => path.replace(new RegExp(`^${context}`), "");

        // 设置响应头用于调试
        config.configure = (proxy, options) => {
            proxy.on("proxyRes", (proxyRes, req) => {
                proxyRes.headers["x-proxy-url"] = new URL(req.url || "", options.target?.toString() || "").href;
            });
        };

        proxyConfig[context] = config;
    }

    return proxyConfig;
}
